package com.aisile.crowd_funding.system.shiro;

import com.aisile.crowd_funding.common.config.Constant;
import com.aisile.crowd_funding.common.utils.MD5Utils;
import com.aisile.crowd_funding.system.pojo.SysUser;
import com.aisile.crowd_funding.system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @标题 MyRealm
 * @作者 Mr.chen
 * @创建日期 2018/12/5 16:19
 * @版本号 1.0
 **/
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /**
     * 授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //根据用户名  去数据库  查用户
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();//用户名

        String password=new String(token.getPassword());

        SysUser user=userService.findByUserName(userName);

        if(user==null){
            //没查到用户
            throw new UnknownAccountException();

        }
        if(!user.getPassword().equals(password)){

            //认证失败

            throw new AccountException();

        }
        if(Constant.USER_STATUS==user.getStatus()){

            //禁用状态
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),getName());


        return info;
    }
        public static void main(String []args){
            String str="123456";

            System.out.println(MD5Utils.encrypt(str));

        }
}
